<template>
  <div class="w-full h-full flex flex-col">
    <div class="flex-1 flex flex-col overflow-hidden" :class="isArmy ? 'login-bg-army' : 'login-bg'">
      <div class="fixed top-0 flex justify-between w-full p-8">
        <div class="flex items-center">
          <img :src="logoIcon || LogoIcon" class="h-8" />
          <span class="ml-4 text-3xl font-medium">{{ appName || '医疗信息系统' }}</span>
        </div>
        <a-space v-if="isShowBtn" class="flex items-center">
          <a-button type="primary" size="small" @click="onMinWindow">最小化</a-button>
          <a-button danger type="primary" size="small" @click="onCloseWindow">关&nbsp;&nbsp;闭</a-button>
        </a-space>
      </div>
      <div class="w-full h-full flex justify-between items-center login-page">
        <div class="w-1/2 pb-60">
          <div class="w-fit text-left mx-auto">
            <div>
              <span v-if="isArmy" class="text-5xl font-bold text-stroke">{{ appName || '医疗信息系统' }}</span>
              <span v-else class="text-5xl font-bold text-stroke">复软智慧一体化</span>
              <span class="text-5xl font-bold text-primary text-stroke"> 医疗平台</span>
            </div>
            <div class="text-3xl font-bold mt-4 text-stroke">Fudansoft iMedicalCare</div>
          </div>
        </div>
        <div class="w-1/2 flex justify-center">
          <a-form class="w-[480px] h-[380px] px-12 py-8 bg-white rounded-lg shadow-md" :model="formState">
            <a-tabs v-model:active-key="activeKey" @change="onChangeTags">
              <a-tab-pane key="1" tab="账号登录">
                <a-form-item name="empId" class="mt-10" :rules="[{ required: true, message: '请输入账号/手机号' }]">
                  <a-input v-model:value="formState.empId" size="large" type="text" placeholder="请输入账号/手机号" :max-length="11" @keyup.enter="onNext">
                    <template #prefix>
                      <UserOutlined />
                    </template>
                  </a-input>
                </a-form-item>
                <a-form-item name="pwd" :rules="[{ required: true, message: '请输入密码' }]">
                  <a-input-password
                    ref="inputPassword"
                    v-model:value="formState.pwd"
                    size="large"
                    autocomplete="new-password"
                    placeholder="请输入密码"
                    :max-length="20"
                    @keyup.enter="onFinish"
                  >
                    <template #prefix>
                      <LockOutlined />
                    </template>
                  </a-input-password>
                </a-form-item>
              </a-tab-pane>
              <a-tab-pane key="2" tab="短信登录">
                <a-form-item name="brMod" class="mt-4" :rules="[{ required: true, message: '请输入手机号' }]">
                  <a-input v-model:value="formState.brMod" size="large" type="text" placeholder="请输入手机号" :max-length="11">
                    <template #prefix>
                      <MobileOutlined />
                    </template>
                  </a-input>
                </a-form-item>
                <a-form-item name="codeImg" :rules="[{ required: true, message: '请输入图形验证码' }]">
                  <a-input v-model:value="formState.codeImg" size="large" type="text" placeholder="请输入图形验证码" :max-length="4">
                    <template #prefix>
                      <LockOutlined />
                    </template>
                    <template #suffix>
                      <div class="code-img">1314</div>
                    </template>
                  </a-input>
                </a-form-item>
                <a-form-item name="code" :rules="[{ required: true, message: '请输入短信验证码' }]">
                  <a-input v-model:value="formState.code" size="large" type="text" placeholder="请输入短信验证码" :max-length="6">
                    <template #prefix>
                      <SafetyOutlined />
                    </template>
                    <template #suffix>
                      <div>
                        <span v-if="!countdown" class="text-primary cursor-pointer text-xs" @click="onClickCode">获取验证码</span>
                        <span v-else class="text-slate-500 cursor-pointer text-xs">重新发送({{ countdown }})</span>
                      </div>
                    </template>
                  </a-input>
                </a-form-item>
              </a-tab-pane>
            </a-tabs>
            <div class="mt-2 flex justify-between items-center">
              <a-checkbox v-model:checked="isRememberPwd">记住密码</a-checkbox>
              <a-popover placement="topLeft" @open-change="getEmpInfo">
                <template #content>
                  <div class="p-4">
                    <div v-if="!(formState.empId && formState.pwd)" class="text-red">请输入账号密码</div>
                    <div v-if="isPwdError" class="text-red">账号密码错误</div>
                    <div v-if="empInfo.empName">
                      <LabelValue label="姓名" :value="empInfo.empName" />
                      <LabelValue label="国家医师编码" :value="empInfo.nmiCode" width="300" />
                      <LabelValue label="医疗机构编码" :value="empInfo.gbFixmedinsCode" width="300" />
                      <LabelValue label="医疗机构名称" :value="empInfo.gbFixmedinsName" width="300" />
                    </div>
                  </div>
                </template>
                <a-button type="link">医疗编码</a-button>
              </a-popover>
            </div>
            <a-form-item :class="activeKey == '1' ? 'mt-8' : 'mt-4'">
              <a-button type="primary" size="large" :loading="loading" block class="py-2 !h-auto" @click="onFinish">登录</a-button>
            </a-form-item>
          </a-form>
        </div>
      </div>
      <footer v-if="!isArmy" class="h-16 flex-center">&copy;2024 版权所有 上海复软科技信息有限公司</footer>
      <footer v-else class="h-16"></footer>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import { UserOutlined, LockOutlined, MobileOutlined, SafetyOutlined } from '@ant-design/icons-vue'
import { post } from '@/utils/request'
import { fetchSystemConfig, getSystemConfig } from '@/utils/systemConfig'
import LogoIcon from '@/assets/images/logo.png'
import useAppStore from '@/store/app'

const ipMac = ref({})

const appStore = useAppStore()
const isShowBtn = ref(false)
const loading = ref(false)
const activeKey = ref('1')
const countdown = ref(0)
const formState = ref({
  empId: '',
  pwd: ''
})

const onChangeTags = (val) => {
  if (val === '1') {
    formState.value = {
      empId: '',
      pwd: ''
    }
  } else {
    formState.value = {}
  }
}

const onClickCode = () => {
  startCountdown()
}

const startCountdown = () => {
  if (countdown.value === 0) {
    countdown.value = 60
    const timer = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--
      } else {
        clearInterval(timer)
      }
    }, 1000)
  }
}
const isRememberPwd = ref(false)

const onFinish = async () => {
  loading.value = true
  const hideLoading = message.loading('登录中...', 0)
  const { code, data, msg } = await post('/login/doLogin', {
    empId: formState.value.empId,
    pwd: Math.floor(Math.random() * 10) + btoa(formState.value.pwd),
    ...ipMac.value
  })
  loading.value = false
  hideLoading()
  if (code === 0) {
    setPwd()
    message.success('登录成功')
    appStore.login(data, '', true)
  } else {
    message.error(msg || '登录失败')
  }
}
const isPwdError = ref(false)
const empInfo = ref({})
const getEmpInfo = async (open) => {
  if (!open) return
  const { code, data } = await post('/login/getlogin', {
    empId: formState.value.empId,
    pwd: Math.floor(Math.random() * 10) + btoa(formState.value.pwd)
  })
  if (code !== 0) return (isPwdError.value = true)
  empInfo.value = data
  isPwdError.value = false
}
const appName = ref('医疗信息系统')
const logoIcon = ref('')
const getPwd = () => {
  const loginInfo = localStorage.getItem('loginInfo')
  if (loginInfo) {
    const { empId, pwd } = JSON.parse(loginInfo)
    formState.value = { empId, pwd }
    isRememberPwd.value = true
  }
}
const setPwd = () => {
  if (isRememberPwd.value) {
    localStorage.setItem('loginInfo', JSON.stringify({ ...formState.value, isRememberPwd: isRememberPwd.value }))
  } else {
    localStorage.removeItem('loginInfo')
  }
}
onMounted(async () => {
  getPwd()
  await fetchSystemConfig()
  appName.value = getSystemConfig('HISNAME') || '医疗信息系统' //系统名称
  document.title = appName.value
  logoIcon.value = getSystemConfig('HOSPITAL_LOGO_URL') //logo
  setIcon(logoIcon.value)
  isShowBtn.value = !!window.openExe
  // if (isDev) {
  //   formState.value = {
  //     empId: '999',
  //     pwd: '123456'
  //   }
  // }
  if (window.openExe) {
    ipMac.value = JSON.parse(window.openExe?.getIPAndMAC()) || {}
  }
})
const setIcon = (icoUrl) => {
  const link = document.querySelector("link[rel*='icon']") || document.createElement('link')
  link.type = 'image/x-icon'
  link.rel = 'shortcut icon'
  link.href = icoUrl
  document.getElementsByTagName('head')[0].appendChild(link)
}
const inputPassword = ref(null)
const onNext = () => {
  inputPassword.value.focus()
}
const onMinWindow = () => {
  window.openExe?.minWindow()
}
const onCloseWindow = () => {
  window.openExe?.closeWindow()
}
const isArmy = getSystemConfig('NAVYHIS_MODE') === '1'
</script>

<style lang="less" scoped>
.login-bg {
  background-image: url(@/assets/images/login-bg.jpg);
  background-size: cover;
}
.login-bg-army {
  background-image: url(@/assets/images/login-bg-army.jpg);
  background-size: cover;
}
.code-img {
  padding: 4px 10px;
  background-color: #e2e1e1;
}
.text-stroke {
  -webkit-text-stroke: 1px #fff;
}
:deep(.ant-tabs-tab-btn) {
  font-size: 18px;
}
:deep(.ant-input-affix-wrapper-lg) {
  padding: 8px 12px;
  font-size: 14px;
  .ant-input-prefix {
    padding-right: 4px;
    color: var(--primary-color);
    font-size: 14px;
  }
}
</style>
